
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:home/assets/r.dart';
import 'package:home/login/user_entity.dart';
import 'package:home/net/base_response_entity.dart';
import 'package:home/net/network.dart';
import 'package:home/page/router.dart';

class LoginPage extends StatefulWidget {

  const LoginPage({Key? key}):super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  ///是否查看密码
  bool _isLookPassword = true;
  ///登录按钮是否可用
  bool _loginButtonEnable = false;
  ///输入框控制器
  late TextEditingController _userNameCtl;
  late TextEditingController _passwordCtl;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _userNameCtl = TextEditingController();
    _passwordCtl = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: SingleChildScrollView(
          child: Container(
            constraints: const BoxConstraints(
              minWidth: double.infinity
            ),
            padding: const EdgeInsets.only(left: 36,top: 100,right: 36),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              children: [
                 Container(
                   width: 100,
                   height: 100,
                   decoration: BoxDecoration(
                     color: Theme.of(context).primaryColor,
                     borderRadius: const BorderRadius.all(Radius.circular(18)),
                       boxShadow: [
                         const BoxShadow(
                             color: Colors.black38,
                             offset: Offset(-10.0, 10.0),
                             blurRadius: 100.0,
                             spreadRadius: 1.0,
                         )
                       ],
                   ),
                   child: Icon(R.icon.loginLogo,color: Colors.white,size: 60,),
                 ),
                const Padding(padding: EdgeInsets.only(top: 36)),
                input(label: "用户名", hintText: "输入用户名",controller: _userNameCtl,onChanged: onChanged,),
                const Padding(padding: EdgeInsets.only(top: 36)),
                input(
                    controller: _passwordCtl,
                    label: "密码",
                    hintText: "请输入密码",
                    obscureText: _isLookPassword,
                    onChanged: onChanged,
                    suffix: CupertinoButton(
                        child: Icon(_isLookPassword?R.icon.editPasswordLook:R.icon.editPasswordUnLook),
                        padding: const EdgeInsets.all(0),
                        minSize: 0,
                        onPressed: (){
                          setState(() {
                            _isLookPassword = !_isLookPassword;
                          });
                        }),
                ),
                Align(
                  alignment: Alignment.topRight,
                  child: CupertinoButton(
                    padding: const EdgeInsets.only(left:8,top:16,right: 0,bottom: 8),
                    child: Text(
                      "手机快捷登录",
                      style: TextStyle(
                          fontSize: 14,
                          color: Theme.of(context).textTheme.headline1?.color
                      ),
                    ),
                    onPressed: (){},
                  ),
                ),
                const Padding(padding: EdgeInsets.only(top: 24)),
                MaterialButton(
                    textColor: Colors.white,
                    color: Theme.of(context).primaryColor,
                    shape: const RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(40))
                    ),
                    disabledColor: Colors.grey.shade400,
                    minWidth: double.infinity ,
                    child: const Text("立即登录"),
                    onPressed: _loginButtonEnable?login:null
                ),
                Stack(
                  children: [
                    Align(
                      alignment: Alignment.topLeft,
                      child: CupertinoButton(
                        padding: const EdgeInsets.only(left:8,top:16,right: 0,bottom: 8),
                        child: Text(
                          "忘记密码",
                          style: TextStyle(
                              fontSize: 14,
                              color: Theme.of(context).textTheme.headline1?.color
                          ),
                        ),
                        onPressed: (){},
                      ),
                    ),Align(
                      alignment: Alignment.topRight,
                      child: CupertinoButton(
                        padding: const EdgeInsets.only(left:8,top:16,right: 0,bottom: 8),
                        child: Text(
                          "注册账号",
                          style: TextStyle(
                              fontSize: 14,
                              color: Theme.of(context).textTheme.headline1?.color
                          ),
                        ),
                        onPressed: register,
                      ),
                    )
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.only(left:24,top: 86,right: 24,bottom: 48),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      IconButton(onPressed: (){}, icon: Icon(R.icon.loginWX,size: 36,),color: Theme.of(context).dividerColor,),
                      IconButton(onPressed: (){}, icon: Icon(R.icon.loginWB,size: 36,),color: Theme.of(context).dividerColor),
                      IconButton(onPressed: (){}, icon: Icon(R.icon.loginQQ,size: 36,),color: Theme.of(context).dividerColor)
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget input({
    required String label,
    required String hintText,
    bool obscureText = false,
    Widget? suffix,
    ValueChanged<String>? onChanged,
    TextEditingController? controller,
  }){
    return Builder(builder: (context){
       return TextField(
         controller: controller,
         onChanged: onChanged,
         obscureText: obscureText,
         keyboardType: TextInputType.visiblePassword,
         decoration: InputDecoration(
             suffix: suffix,
             floatingLabelBehavior: FloatingLabelBehavior.always,
             focusedBorder: defaultInputBorder(),
             focusedErrorBorder: defaultInputBorder(),
             enabledBorder: defaultInputBorder(),
             contentPadding: const EdgeInsets.only(left: 8,right: 8),
             labelText: label,
             hintText: hintText
         ),
       );
    });
  }

  InputBorder defaultInputBorder(){
    return UnderlineInputBorder(
        borderSide: BorderSide(width: 0.5,color: Theme.of(context).dividerColor)
    );
  }

  onChanged(String changed){
    String userName = _userNameCtl.value.text.trim();
    String password = _passwordCtl.value.text.trim();
    setState(() {
      _loginButtonEnable = userName.length > 3 && password.length > 5;
    });

  }

  ///注册页面
  register(){
      Navigator.pushNamed(context, StationRouter.register).then((value){
        if(value is bool && value){
          Navigator.pushReplacementNamed(context, StationRouter.home);
        }
      });
  }

  ///登录
  login(){
    String userName = _userNameCtl.value.text.trim();
    String password = _passwordCtl.value.text.trim();
    if(userName.isEmpty || password.isEmpty){
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("请输入 用户名密码")));
      return;
    }
    NetWork.getInstance().post<User>("/login",
            queryParameters: {"name":userName,"password":password},
            )
        .then((value){
            print(value.data);
            if(value.code == SUCCESS_CODE){
              var channel = ModalRoute.of(context)?.settings.arguments;
              if(channel == null) {
                Navigator.pushReplacementNamed(context, StationRouter.home);
              }else{
                Navigator.pop(context,true);
              }
            }else{
              ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(value.message)));
            }
        });

  }
}
